import os, re

def parse_state(l, state):
  l = l.strip()
  if l in ['--TEST--', '--CSS--', '--EXPECT--', '--SETTINGS--']:
    return l
  return state

def parse_csst(filename):
  f = open(filename, 'r')
  print filename
  css = open('tmp.css', 'w')
  state = ''
  for l in f:
    old_state = state
    state = parse_state(l, state)
    if old_state != state or state == '':
      continue
    elif state == '--TEST--':
      print l
      continue
    elif state == '--SETTINGS--':
      l = l.strip()
      global settings
      if re.match('optimise_shorthands', l):
        settings += ' --' + l
      if re.match('discard_invalid_properties', l):
        settings += ' --' + l
      continue
    elif state == '--CSS--':
      css.write(l.strip())
      continue
    elif state == '--EXPECT--':
      pass
      m = re.search('\'([\w-]+)\'.+\'(.+)\'', l)
      if m:
        str = m.group(1) + ':' + m.group(2) + ';'
        test.append(str.strip())

def strip_line(l): return l.strip()

def test_file(filename):
  global settings
  global test
  parse_csst(filename)

  os.system('csstidy.exe tmp.css out.css --silent=true ' + settings)
  os.remove('tmp.css')

  t = open('out.css', 'r')
  tmp = t.readlines()
  tmp = map(strip_line, tmp)
  noerr = True
  for line in test:
    if line not in tmp:
      noerr = False
      print line + ' not work'
  if noerr:
    print 'Ok'
    global test_success
    test_success += 1
  else:
    global test_failure
    test_failure += 1
  print
  print
  test = []
  settings = ' '


test = []
settings = ' '

test_success = 0
test_failure = 0

for curdir, subdirs, files in os.walk(os.getcwd()):
  for file in files:
    test_file(os.path.join(curdir, file))

#os.remove('out.css')

print 'Test total: ', test_failure + test_success
print 'Test success: ', test_success
print 'Test failure: ', test_failure
  